<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="数据预处理——缺失值处理案例来源：《Python数据分析与挖掘实战》第6章 电力窃漏电用户自动识别 这里介绍一种缺失值处理手段：插补法，具体是拉格朗日插值法 拉格朗日插值法补值的具体方法如下： 首先从原始数据集中确定因变量和自变量，取出缺失值前后5个数据（前后数据中遇到数据不存在或者为空的，直接将数据舍去，将仅有的数据组成一组）,根据取出来的10个数据组成一组。然后采用拉格朗日多项式插值公式">
<meta property="og:type" content="article">
<meta property="og:title" content="拉格朗日插值法-Python">
<meta property="og:url" content="http://yoursite.com/2020/07/07/lagrange-interpolation/index.html">
<meta property="og:site_name" content="Zhimin">
<meta property="og:description" content="数据预处理——缺失值处理案例来源：《Python数据分析与挖掘实战》第6章 电力窃漏电用户自动识别 这里介绍一种缺失值处理手段：插补法，具体是拉格朗日插值法 拉格朗日插值法补值的具体方法如下： 首先从原始数据集中确定因变量和自变量，取出缺失值前后5个数据（前后数据中遇到数据不存在或者为空的，直接将数据舍去，将仅有的数据组成一组）,根据取出来的10个数据组成一组。然后采用拉格朗日多项式插值公式">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://i.loli.net/2020/07/07/ZqiVEzFQOemxh32.png">
<meta property="og:image" content="https://i.loli.net/2020/07/07/wLF8MasC9O3JrpZ.png">
<meta property="og:image" content="https://i.loli.net/2020/07/07/6RpJEyAUbrwtv3n.png">
<meta property="og:image" content="https://i.loli.net/2020/07/07/PtWmGLjDQe2EH5X.png">
<meta property="article:published_time" content="2020-07-07T14:11:40.000Z">
<meta property="article:modified_time" content="2020-07-07T15:14:38.166Z">
<meta property="article:author" content="ZHIMIN TU">
<meta property="article:tag" content="拉格朗日插值">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2020/07/07/ZqiVEzFQOemxh32.png">

<link rel="canonical" href="http://yoursite.com/2020/07/07/lagrange-interpolation/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'en'
  };
</script>

  <title>拉格朗日插值法-Python | Zhimin</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Zhimin</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="en">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/07/07/lagrange-interpolation/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="ZHIMIN TU">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zhimin">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          拉格朗日插值法-Python
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>
              

              <time title="Created: 2020-07-07 22:11:40 / Modified: 23:14:38" itemprop="dateCreated datePublished" datetime="2020-07-07T22:11:40+08:00">2020-07-07</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="数据预处理——缺失值处理"><a href="#数据预处理——缺失值处理" class="headerlink" title="数据预处理——缺失值处理"></a>数据预处理——缺失值处理</h2><p>案例来源：<strong>《Python数据分析与挖掘实战》第6章 电力窃漏电用户自动识别</strong></p>
<p>这里介绍一种缺失值处理手段：插补法，具体是<strong>拉格朗日插值法</strong></p>
<p>拉格朗日插值法补值的具体方法如下：</p>
<p>首先从原始数据集中确定因变量和自变量，取出缺失值前后5个数据（前后数据中遇到数据不存在或者为空的，直接将数据舍去，将仅有的数据组成一组）,根据取出来的10个数据组成一组。然后采用拉格朗日多项式插值公式</p>
<p><img src="https://i.loli.net/2020/07/07/ZqiVEzFQOemxh32.png" alt="image-20200707222902831"></p>
<p><img src="https://i.loli.net/2020/07/07/wLF8MasC9O3JrpZ.png" alt="image-20200707222936410"></p>
<p>其中，x为缺失值对应的下标序号，Ln(x)为缺失值的插值结果，xi为非缺失值yi的下标序号。对全部缺失数据依次进行插补，直到不存在缺失值为止。数据插补代码如代码文件6-1_Lagrange_interpolation.py所示。</p>
<p>配套教材原始代码6-1_Lagrange_interpolation.py</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">#-*- coding: utf-8 -*-</span><br><span class="line">#拉格朗日插值代码</span><br><span class="line">import pandas as pd #导入数据分析库Pandas</span><br><span class="line">from scipy.interpolate import lagrange #导入拉格朗日插值函数</span><br><span class="line"></span><br><span class="line">inputfile &#x3D; &#39;..&#x2F;data&#x2F;missing_data.xls&#39; #输入数据路径,需要使用Excel格式；</span><br><span class="line">outputfile &#x3D; &#39;..&#x2F;tmp&#x2F;missing_data_processed.xls&#39; #输出数据路径,需要使用Excel格式</span><br><span class="line"></span><br><span class="line">data &#x3D; pd.read_excel(inputfile, header&#x3D;None) #读入数据</span><br><span class="line"></span><br><span class="line">#自定义列向量插值函数</span><br><span class="line">#s为列向量，n为被插值的位置，k为取前后的数据个数，默认为5</span><br><span class="line">def ployinterp_column(s, n, k&#x3D;5):</span><br><span class="line">  y &#x3D; s[list(range(n-k, n)) + list(range(n+1, n+1+k))] #取数</span><br><span class="line">  y &#x3D; y[y.notnull()] #剔除空值</span><br><span class="line">  return lagrange(y.index, list(y))(n) #插值并返回插值结果</span><br><span class="line"></span><br><span class="line">#逐个元素判断是否需要插值</span><br><span class="line">for i in data.columns:</span><br><span class="line">  for j in range(len(data)):</span><br><span class="line">    if (data[i].isnull())[j]: #如果为空即插值。</span><br><span class="line">      data[i][j] &#x3D; ployinterp_column(data[i], j)</span><br><span class="line"></span><br><span class="line">data.to_excel(outputfile, header&#x3D;None, index&#x3D;False) #输出结果</span><br></pre></td></tr></table></figure>

<p>运行之后出现</p>
<img src="https://i.loli.net/2020/07/07/6RpJEyAUbrwtv3n.png" alt="image-20200707224536149" style="zoom: 67%;" />

<p><img src="https://i.loli.net/2020/07/07/PtWmGLjDQe2EH5X.png" alt="image-20200707224457575"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">KeyError: &#39;Passing list-likes to .loc or [] with any missing labels is no longer supported, see https:&#x2F;&#x2F;pandas.pydata.org&#x2F;pandas-docs&#x2F;stable&#x2F;user_guide&#x2F;indexing.html#deprecate-loc-reindex-listlike&#39;</span><br></pre></td></tr></table></figure>

<p>我的解决过程：</p>
<ol>
<li><p>将上面出错内容进行搜索，找到以下有用的内容</p>
<p><a href="https://stackoverflow.com/questions/61291741/passing-list-likes-to-loc-or-with-any-missing-labels-is-no-longer-supported" target="_blank" rel="noopener">尝试reindex</a></p>
</li>
<li><p>改写代码</p>
<p>将</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">y &#x3D; s[list(range(n-k, n)) + list(range(n+1, n+1+k))]</span><br></pre></td></tr></table></figure>

<p>改写成</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">y &#x3D; s.reindex(list(range(n - k, n)) + list(range(n + 1, n + 1 + k)))</span><br></pre></td></tr></table></figure></li>
</ol>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E6%8B%89%E6%A0%BC%E6%9C%97%E6%97%A5%E6%8F%92%E5%80%BC/" rel="tag"># 拉格朗日插值</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/07/07/Useridentification/" rel="prev" title="Useridentification">
      <i class="fa fa-chevron-left"></i> Useridentification
    </a></div>
      <div class="post-nav-item"></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#数据预处理——缺失值处理"><span class="nav-number">1.</span> <span class="nav-text">数据预处理——缺失值处理</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">ZHIMIN TU</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">9</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">tags</span>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ZHIMIN TU</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
